import { get, post, put, del } from './request'

/**
 * Leave Application DTOs
 */
export interface LeaveApplicationQueryParams {
  current?: number
  size?: number
  leaveNo?: string
  applicantId?: number
  leaveType?: string
  currentStatus?: string
  submitStartTime?: string
  submitEndTime?: string
}

export interface LeaveApplicationDetail {
  id: number
  leaveNo?: string
  applicantId: number
  applicantName?: string
  applicantDeptName?: string
  applicantPosition?: string
  leaveTypeName?: string
  flowTemplateId?: number
  flowTemplateName?: string
  flowTemplateCode?: string
  startTime?: string
  endTime?: string
  totalDays?: number
  reason?: string
  location?: string
  currentStatus?: string
  currentStep?: string
  currentStepOrder?: number
  currentApproverName?: string
  nextStepName?: string
  submitTime?: string
  remark?: string
  companyId?: number
  companyName?: string
  departmentId?: number
  departmentName?: string
  temporaryContactPerson?: string
  temporaryContactPosition?: string
  temporaryContactPhone?: string
  reportingContactPerson?: string
  reportingContactPhone?: string
  isInternal?: number // 是否内部请假：0-是（内部单位），1-否（外部单位）
  attachments?: LeaveApplicationAttachment[]
  approvalRecords?: LeaveApplicationApprovalRecord[]
}

export interface LeaveApplicationAttachment {
  id?: number
  leaveId?: number
  fileName: string
  filePath: string
  fileUrl?: string
  fileSize?: number
  fileType?: string
  uploadUserId?: number
  uploadUserName?: string
  uploadTime?: string
}

export interface LeaveApplicationApprovalRecord {
  id?: number
  leaveId?: number
  stepName?: string
  stepOrder?: number
  approverName?: string
  approverRoleName?: string
  opinion?: string
  decision?: string
  approveTime?: string
  operateTime?: string
  submitTime?: string
  isCurrent?: number // 是否为当前有效记录：1-是，0-否
}

export interface LeaveTemplateSimple {
  id: number
  templateCode: string
  templateName: string
  description?: string
}

export interface LeaveApplicationFormData {
  id?: number
  companyId: number
  companyName: string
  departmentId: number
  departmentName: string
  applicantId: number
  applicantName: string
  applicantPosition?: string
  leaveTypeId: number
  leaveTypeName: string
  flowTemplateId: number
  flowTemplateName: string
  startTime: string
  endTime: string
  totalDays: number
  reason: string
  location?: string
  temporaryContactPerson?: string
  temporaryContactPosition?: string
  temporaryContactPhone?: string
  reportingContactPerson?: string
  reportingContactPhone?: string
  isInternal?: number
  remark?: string
}

export interface LeaveApplicationSubmitData {
  id: number
  applicantId: number
  targetStepOrder?: number | null
  targetStepName?: string | null
  action?: 'approve' | 'reject'
  opinion?: string
  selectedApprovers?: Array<{
    approverId: number
    approverName: string
    deptName?: string
    stepOrder?: number | null
    stepName?: string | null
  }>
}

export interface LeaveApplicationNextStepPreviewRequest {
  leaveId: number
  operatorId: number
  currentStepOrder?: number | null
  currentStepName?: string | null
  nextStepName?: string | null
}

export interface LeaveApplicationApproverOption {
  userId: number
  userName: string
  jobTitle?: string
  deptName?: string
  phone?: string
}

/**
 * Leave APIs
 */
export const getMyLeaveApplications = (
  applicantId: number,
  status?: string,
  pageNum: number = 1,
  pageSize: number = 10,
  submitStartTime?: string,
  submitEndTime?: string,
) => {
  const query: Record<string, string> = {
    applicantId: String(applicantId),
    pageNum: String(pageNum),
    pageSize: String(pageSize),
  }
  if (status) {
    query.status = status
  }
  if (submitStartTime) {
    query.submitStartTime = submitStartTime
  }
  if (submitEndTime) {
    query.submitEndTime = submitEndTime
  }
  const queryString = Object.entries(query)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&')
  return get(`/leave/application/my${queryString ? `?${queryString}` : ''}`)
}

export const getLeaveApplicationPage = (params: LeaveApplicationQueryParams) => {
  return get('/leave/application/page', params)
}

export const getLeaveApplicationDetail = (id: number) => {
  return get(`/leave/application/${id}`)
}

export const getEnabledLeaveTemplates = () => {
  return get('/leave/template/enabled')
}

// #ifdef H5
const buildLeaveFormData = (payload: LeaveApplicationFormData, files?: File[]) => {
  const formData = new FormData()
  formData.append('request', new Blob([JSON.stringify(payload)], { type: 'application/json' }))
  ;(files || []).forEach((file) => {
    formData.append('files', file)
  })
  return formData
}
// #endif

export const createLeaveApplication = (data: LeaveApplicationFormData, files?: File[]) => {
  // #ifdef H5
  // H5 平台：使用 FormData
  if (files && files.length > 0) {
    const formData = buildLeaveFormData(data, files)
    return post('/leave/application', formData, {
      header: { 'Content-Type': 'multipart/form-data' },
    })
  } else {
    // H5 平台：没有文件时，也使用 FormData（后端要求）
    const formData = buildLeaveFormData(data, [])
    return post('/leave/application', formData, {
      header: { 'Content-Type': 'multipart/form-data' },
    })
  }
  // #endif

  // #ifndef H5
  // 非 H5 平台：不传文件时，使用 UniApp 专用接口发送 JSON
  return post('/leave/application/uniapp-create', data, {
    header: { 'Content-Type': 'application/json' },
  })
  // #endif
}

export const updateLeaveApplication = (data: LeaveApplicationFormData, files?: File[]) => {
  // #ifdef H5
  // H5 平台：使用 FormData
  if (files && files.length > 0) {
    const formData = buildLeaveFormData(data, files)
    return put('/leave/application', formData, {
      header: { 'Content-Type': 'multipart/form-data' },
    })
  } else {
    // H5 平台：没有文件时，也使用 FormData（后端要求）
    const formData = buildLeaveFormData(data, [])
    return put('/leave/application', formData, {
      header: { 'Content-Type': 'multipart/form-data' },
    })
  }
  // #endif

  // #ifndef H5
  // 非 H5 平台：不传文件时，使用 UniApp 专用接口发送 JSON
  return put('/leave/application/uniapp-update', data, {
    header: { 'Content-Type': 'application/json' },
  })
  // #endif
}

export const deleteLeaveApplication = (id: number, applicantId: number) => {
  // 将 applicantId 作为查询参数拼接到 URL
  return del(`/leave/application/${id}?applicantId=${applicantId}`)
}

/** 提交审批参数 */
export interface LeaveApplicationSubmitData {
  id: number // 请假ID
  applicantId: number // 申请人ID
  targetStepOrder?: number | null // 目标步骤序号（用于选人或跳过）
  targetStepName?: string | null // 目标步骤名称（可选）
  action?: 'approve' | 'reject' // 提交流程的动作
  opinion?: string // 提交意见
  selectedApprovers?: Array<{
    approverId: number
    approverName: string
    deptName?: string
    stepOrder?: number | null
    stepName?: string | null
  }>
}

/** 预检下一步骤请求 */
export interface LeaveApplicationNextStepPreviewRequest {
  leaveId: number
  operatorId: number
  currentStepOrder?: number | null
  currentStepName?: string | null
  nextStepName?: string | null
}

/** 审批人候选项 */
export interface LeaveApplicationApproverOption {
  userId: number
  userName: string
  jobTitle?: string
  phone?: string
  deptName?: string
}

/** 预检下一步骤响应 */
export interface LeaveApplicationNextStepPreview {
  currentStepName?: string
  currentStepOrder?: number
  currentApproverRoleName?: string
  nextStepName?: string
  nextStepOrder?: number
  nextApproverRoleName?: string
  needsSelection: boolean // 下一步骤是否需要选择人员
  currentStepNeedsSelection?: boolean // 当前步骤是否需要选择人员
  approverOptions: LeaveApplicationApproverOption[]
}

/** 退回操作参数 */
export interface LeaveApplicationRejectData {
  leaveId: number // 请假ID
  approverId: number // 审批人ID
  approverName: string // 审批人姓名
  opinion?: string // 退回意见
  returnToStepName?: string // 退回步骤名称
}

export const submitLeaveApplication = (payload: LeaveApplicationSubmitData) => {
  return post('/leave/application/submit', payload)
}

export const previewLeaveApplicationNextStep = (
  payload: LeaveApplicationNextStepPreviewRequest,
) => {
  return post('/leave/application/next-step/preview', payload)
}

export const rejectLeaveApplication = (payload: LeaveApplicationRejectData) => {
  return post('/leave/application/reject', payload)
}

export const deleteLeaveAttachment = (attachmentId: number) => {
  return del(`/leave/application/attachment/${attachmentId}`)
}

/**
 * 获取待我审批的请假申请列表
 */
export const getPendingLeaveApprovals = (
  approverId: number,
  pageNum: number = 1,
  pageSize: number = 10,
) => {
  return get(
    `/leave/application/pending?approverId=${approverId}&pageNum=${pageNum}&pageSize=${pageSize}`,
  )
}

/**
 * 获取可退回的步骤列表
 */
export interface ReturnableStep {
  stepName: string
  stepOrder: number
}

export const getReturnableSteps = (leaveId: number, currentStepOrder: number) => {
  return get('/leave/application/returnable-steps', { leaveId, currentStepOrder })
}

/**
 * 获取当前用户正在进行中的请假申请及其审批流程
 */
export const getCurrentInProgressApplication = (applicantId: number) => {
  return get(`/leave/application/current-in-progress?applicantId=${applicantId}`)
}

/**
 * 获取我的审批历史
 */
export const getMyLeaveApprovalHistory = (
  approverId: number,
  pageNum: number = 1,
  pageSize: number = 10,
  params?: {
    applicantName?: string
    departmentName?: string
    year?: number
    month?: number
  },
) => {
  let url = `/leave/application/history?approverId=${approverId}&pageNum=${pageNum}&pageSize=${pageSize}`

  if (params?.applicantName) {
    url += `&applicantName=${encodeURIComponent(params.applicantName)}`
  }
  if (params?.departmentName) {
    url += `&departmentName=${encodeURIComponent(params.departmentName)}`
  }
  if (params?.year) {
    url += `&year=${params.year}`
  }
  if (params?.month) {
    url += `&month=${params.month}`
  }

  return get(url)
}
